<template>
    <div>
        <el-pagination @size-change="onSizeChange" @current-change="onCurrentChange" :current-page.sync="pageNum"
            :page-sizes="[20, 40, 80, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="maxRows" background :pager-count="7">
        </el-pagination>
    </div>
</template>


<script>
/***
 * 一个回调 两个方法
 * <pager :doQuery="function(pageNum,pageSize)"></pager>
 * //doQuery回调中请求服务器,刷新table页面,同时调pager控件的setMaxRows方法刷新Pager
 * doQuery(pageNum,pageSize){
 *  //请求服务器
 *  service({
        ws: false,
        url: '/test/paging',
        method: 'get',
        params: { pageSize: pageSize, pageNum: pageNum }
      })
        .then(res => {
            this.tableData = res.data
            //此处调setMaxRows刷新pager
            this.$refs.pager.setMaxRows(res.maxRows)
        })
        .catch(err => {
          console.error(err);
        })
 * }
 * 
 * pager中存在一个reload方法重置状态
 * 
 * 
 * 
 * 
 ***/
export default {
    name: "paging",
    props: {
        doQuery: Function
    },
    data() {
        return {
            query: this.doQuery,
            pageSize: 20,
            pageNum: 0,
            maxRows: 0,
            maxPage: 0
        }
    },
    methods: {
        setMaxRows(maxRows) {
             
            if (this.pageSize > maxRows) {
                this.pageSize = maxRows
                this.pageNum = 1
                this.maxRows = maxRows
                this.maxPage = 1
            } else {
                this.maxRows = maxRows
                this.maxPage = Math.ceil(maxRows / this.pageSize) + 1
            }
        },
        //刷新table中数据
        reload() {
            this.pageNum = 1
            this.pageSize = 20
            //狠奇怪,这个query调用时候上下文是父控件
            //而不是本控件
            this.query.apply(this.$parent, [this.pageNum, this.pageSize]);
        },
        onSizeChange(val) {
            if (val > this.maxRows) {
                this.pageSize = this.maxRows
            } else {
                this.pageSize = val
            }
            this.pageNum = 1
            this.query.apply(this.$parent, [this.pageNum, this.pageSize]);
        },
        onCurrentChange(val) {
            //不可输入超过最大页数的值
            if (val > this.maxPage) {
                this.pageNum = this.maxPage
            } else if (val < 0) {
                this.pageNum = 1
            } else {
                this.pageNum = val
            }
            this.query.apply(this.$parent, [this.pageNum, this.pageSize]);
        },
    }
}

</script>